<template>
  <div>
    <a-card>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="5" :sm="24">
              <a-form-item label="分组">
                <a-input v-model="queryParam.f_appgroup" placeholder="请输入分组" />
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="参数名">
                <a-input v-model="queryParam.f_appname" placeholder="请输入参数名" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="描述">
                <a-input v-model="queryParam.f_describe" placeholder="请输入描述" />
              </a-form-item>
            </a-col>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" @click="searchHa_appsetting" icon="search">查询</a-button>
                <a-button icon="reload" style="margin-left: 8px" @click="reQuery">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div style="margin-bottom: 16px">
        <a-button v-auth:ha_appsetting_add type="primary" style="margin-left: 8px" @click="handleAdd" icon="plus"
          >添加系统配置</a-button
        >

        <a-button v-auth:ha_appsetting_list type="primary" style="margin-left: 8px" @click="exportExcel" icon="export"
          >导出系统配置</a-button
        >
        <a-button v-auth:ha_appsetting_list type="primary" style="margin-left: 8px" @click="refreshCache" icon="sync"
          >清除缓存</a-button
        >
      </div>
      <a-table
        :scroll="{ x: 1500, y: 300 }"
        :columns="ucolumns"
        :data-source="udata"
        :pagination="upagination"
        :loading="loading"
        rowKey="id"
        @change="tableChange"
        size="middle"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ (upagination.current - 1) * upagination.pageSize + parseInt(index) + 1 }}
        </span>
        <span slot="operation" slot-scope="text, record">
          <template>
            <a v-auth:ha_appsetting_save @click="handleEdit(record, false)">编辑</a>
          </template>
        </span>
      </a-table>
    </a-card>
    <a-drawer
      :title="isView ? '系统配置详情' : '系统配置编辑'"
      :width="720"
      :visible="visible"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
      destroyOnClose
    >
      <edit ref="view" @close="onClose" @reloadList="searchHa_appsetting"></edit>
    </a-drawer>

    <a-drawer
      title="清除缓存"
      :width="720"
      :visible="isCacheVisible"
      :body-style="{ paddingBottom: '80px' }"
      @close="
        () => {
          isCacheVisible = false
        }
      "
      destroyOnClose
    >
      <a-row v-for="(value, key) in cacheMap" :key="key">
        <a-form-model-item
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 18 }"
          :label="value"
          prop="appgroup"
          has-feedback
        >
          <a-popconfirm title="确定清除吗？" ok-text="确定" cancel-text="取消" @confirm="cleanCache(key)">
            <a href="javascript:void(0);">清除</a>
          </a-popconfirm>
        </a-form-model-item>
      </a-row>
    </a-drawer>
  </div>
</template>

<style lang="less" src="@/style/base.less">
</style>

<script>
import {
  delHa_appsettings,
  delHa_appsetting,
  queryHa_appsettingList,
  output,
  downloadModal,
  importModal,
} from '@/api/base/ha_appsetting'
import { cleanByKey } from '@/api/base/cache.js'
import edit from '@/views/base/Ha_appsettingEdit'
// 没有用到枚举作为查询条件的请删除
import { queryEnumerationValuesByName } from '@/api/base/enumeration'
import { FILETYPE, FILESIZE } from '@/store/mutation-types'

export default {
  data() {
    return {
      cacheMap: {
        'CACHE_USERS': '用户姓名缓存', // 用户姓名缓存
        'CACHE_GROUPS': '角色缓存', // 角色缓存
        'CACHE_GROUPUSERS': '根据角色id缓存组内成员', // 根据角色id缓存组内成员的key
        'CACHE_DATASOURES': '数据源缓存', // 数据源缓存
        'CACHE_BTNLIST': '流程默认系统按钮列表', // 流程默认系统按钮列表
        'USERINFO:MANAGER': '系统管理员列表', // 系统管理员
      }, // reads缓存定义key
      isCacheVisible: false, // 缓存设置抽屉 显示/隐藏
      advanced: false, // 查询条件是否展开
      loading: false, // 遮罩是否显示
      visible: false, // 抽屉是否可见
      ubordered: true, // 表格边框是否显示
      isView: false, // 是否查看
      queryParam: {}, // 查询条件
      selectedRowKeys: [], // 选中的行id
      udata: [], // 表格数据
      upagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: (total) => `共${total}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
      },
      ucolumns: [
        {
          title: '序号',
          width: '50px',
          align: 'center',
          fixed: 'left',
          scopedSlots: { customRender: 'serial' },
        },

        {
          title: '分组',
          dataIndex: 'appgroup',
          width: '1',
          sorter: (a, b) => String(a.appgroup).localeCompare(String(b.appgroup)),
          align: 'left',
        },
        {
          title: '参数名',
          dataIndex: 'appname',
          width: '1',
          sorter: (a, b) => String(a.appname).localeCompare(String(b.appname)),
          align: 'left',
        },
        {
          title: '参数值',
          dataIndex: 'appvalue',
          width: '1',
          sorter: (a, b) => String(a.appvalue).localeCompare(String(b.appvalue)),
          align: 'left',
        },
        {
          title: '描述',
          dataIndex: 'describe',
          width: '1',
          sorter: (a, b) => String(a.describe).localeCompare(String(b.describe)),
          align: 'left',
        },
        {
          title: '数据类型',
          dataIndex: 'datatype',
          width: '1',
          sorter: (a, b) => String(a.datatype).localeCompare(String(b.datatype)),
          align: 'center',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '60px',
          fixed: 'right',
          scopedSlots: { customRender: 'operation' },
        },
      ], // 表头
      importVisible: false, //是否显示导入数据弹窗
      importExcelFile: {}, //导入模板文件
    }
  },
  created() {
    // 没有用到枚举作为查询条件的请删除
    this.findEnumByName()
    this.findHa_appsettingList(this.queryParam)
  },
  methods: {
    // 清除缓存
    cleanCache(key) {
      console.log('key', key)
      cleanByKey(key).then((res) => {
        if (res.code == 0) {
          this.$message.success('清除成功')
        }
      })
    },
    // 显示清除缓存抽屉
    refreshCache() {
      this.isCacheVisible = true
    },
    /**
     *  查询枚举值,没有用到枚举作为查询条件的请删除
     */
    findEnumByName() {
      const parameter = []
      parameter.forEach((item) => {
        queryEnumerationValuesByName({ enName: item.enumName }).then((res) => {
          console.log('query' + item.enumName, res.data)
          this[`${item.enname}List`] = res.data
          this[`${item.enname}List`].unshift({ id: '', describe: '全部' })
          console.log(this[`${item.enname}List`])
        })
      })
    },
    /**
     *  查询系统配置列表
     */
    findHa_appsettingList(queryParam) {
      const a = Date.now()
      console.log('queryParam', queryParam)
      queryHa_appsettingList(queryParam).then((res) => {
        this.loading = true
        console.log('queryHa_appsettingList:', res.data)
        this.udata = res.data.records
        // 将当前页码和数量与后台绑定
        this.upagination.total = res.data.total
        this.upagination.current = res.data.current
        this.upagination.pageSize = res.data.size
        // 如果查询时间太短就给一个0.5秒的加载效果
        const b = Date.now()
        if (b - a < 500) {
          setTimeout(() => {
            this.loading = false
          }, 500)
        } else {
          this.loading = false
        }
      })
    },
    /**
     * 重置查询条件并查询数据
     */
    reQuery() {
      this.queryParam = {}
      this.findHa_appsettingList(this.queryParam)
    },
    /**
     * 翻页、设置页数量时触发，将分页组建的当前页与大小传给后台
     */
    tableChange(pagination, filters, sorter, { currentDataSource }) {
      console.log('tableChange', pagination)
      console.log('filters', filters)
      console.log('sorter', sorter)
      console.log('{ currentDataSource }', { currentDataSource })
      this.queryParam.pageNumber = pagination.current
      this.queryParam.pageSize = pagination.pageSize
      if (sorter != null && sorter.order != null) {
        this.queryParam.sort = sorter.field
        this.queryParam.order = sorter.order
      }
      this.findHa_appsettingList(this.queryParam)
    },
    /**
     * 查询
     */
    searchHa_appsetting() {
      // 查询时将当前页码重置为1，否则会出现有数据但不显示的问题
      this.queryParam.pageNumber = 1
      // this.upagination.current = 1
      this.findHa_appsettingList(this.queryParam)
    },
    /**
     * 选中行数据时触发
     */
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    /**
     * 打开抽屉
     */
    showDrawer() {
      this.visible = true
    },
    /**
     * 收回抽屉
     */
    onClose() {
      this.visible = false
    },
    /**
     * 进入新增页面
     */
    handleAdd() {
      this.showDrawer()
      setTimeout(() => {
        this.$refs.view.resetHa_appsetting()
      }, 10)
    },
    /**
     * 进入编辑页面
     */
    handleEdit(res, isView) {
      this.isView = isView
      console.log('view', res.id)
      this.showDrawer()
      setTimeout(() => {
        this.$refs.view.findHa_appsettingById(res.id, isView)
      }, 10)
    },
    /**
     * 删除系统配置
     */
    delHa_appsettingById(res) {
      delHa_appsetting(res.id).then((res) => {
        console.log('delHa_appsetting:', res)
        if (res.code !== 0) {
          this.$message.success(res.msg)
        } else {
          this.selectedRowKeys = []
          this.searchHa_appsetting()
          this.$message.success('删除成功')
        }
      })
    },
    /**
     * 批量删除系统配置
     */
    delHa_appsettings() {
      delHa_appsettings({ ids: this.selectedRowKeys.toString() }).then((res) => {
        console.log('delHa_appsettings:', res)
        if (res.code !== 0) {
          this.$message.success(res.msg)
        } else {
          this.selectedRowKeys = []
          this.searchHa_appsetting()
          this.$message.success('删除成功')
        }
      })
    },
    /**
     * 显示导入弹窗
     */
    showImport() {
      this.importVisible = true
      this.importExcelFile = {} //置空导入模板文件
    },
    /**
     * 确定保存导入数据
     */
    handleImportOk() {
      this.importExcel()
      this.importVisible = false
    },
    /**
     * 拖拽验证文件类型
     */
    handleImportReject(file) {
      this.beforeImportUpload(file)
    },
    /**
     * 上传导入文件前验证文件类型
     */
    beforeImportUpload(file) {
      return new Promise((resolve, reject) => {
        //文件格式是否为xls、xlsx
        let isAcceptType =
          file.type === 'application/vnd.ms-excel' ||
          file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        let acceptType = 'xls、xlsx'
        if (!isAcceptType) {
          this.$message.warning('请上传' + acceptType + '格式文件')
          return reject(false)
        }
        //文件小于20M
        let isLtSize = file.size / 1024 / 1024 < FILESIZE
        if (!isLtSize) {
          this.$message.warning('请上传' + FILESIZE + 'MB以内的文件')
          return reject(false)
        }
        this.importExcelFile = file
        return resolve(false)
      })
    },
    /**
     *	导入Excel
     */
    importExcel() {
      const importExcel = this.$message.loading('正在导入中...', 0)
      // console.log('this.importExcelFile', this.importExcelFile)
      importModal(this.importExcelFile).then((res) => {
        if (res.code == 0) {
          setTimeout(importExcel, 0)
          this.searchHa_appsetting()
          this.$message.success('导入成功')
        } else {
          setTimeout(importExcel, 0)
          this.$message.error('导入失败')
        }
      })
    },
    /**
     *	下载导入模板
     */
    downloadExcelModal() {
      downloadModal()
        .then((response) => {
          var blob = new Blob([response])
          var downloadElement = document.createElement('a')
          var href = window.URL.createObjectURL(blob) //创建下载的链接
          downloadElement.href = href
          downloadElement.download = '系统配置-导入模板.xls' //下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
          window.URL.revokeObjectURL(href) //释放掉blob对象
        })
        .catch(function () {
          console.log(error)
        })
    },
    /**
     *  导出Excel
     */
    exportExcel() {
      output(this.queryParam)
        .then((response) => {
          var blob = new Blob([response])
          var downloadElement = document.createElement('a')
          var href = window.URL.createObjectURL(blob) //创建下载的链接
          downloadElement.href = href
          downloadElement.download = '系统配置.xls' //下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
          window.URL.revokeObjectURL(href) //释放掉blob对象
        })
        .catch(function () {
          console.log(error)
        })
    },
  },
  components: {
    edit,
  },
}
</script>